package lv.usbpermission;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.concurrent.TimeUnit;

import io.reactivex.Completable;
import io.reactivex.CompletableEmitter;
import io.reactivex.CompletableOnSubscribe;
import io.reactivex.CompletableSource;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Single;
import io.reactivex.SingleEmitter;
import io.reactivex.SingleOnSubscribe;
import io.reactivex.SingleSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class DialogActivity extends AppCompatActivity {

    private final CompositeDisposable compositeDisposable = new CompositeDisposable();
    private ProgressDialog progressDialog;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setTitle("");
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        if (getIntent().getBooleanExtra("reboot", false)) {
            new AlertDialog.Builder(DialogActivity.this).setTitle("提示").setMessage("首次使用加载USB权限模块，点击确定将重启机器，激活USB模块").setCancelable(false).setPositiveButton("确定", (dialog, which) -> UsbPermission.reBoot()).show();
        } else {
            progressDialog = ProgressDialog.show(DialogActivity.this, "提示", "正在加载USB权限模块", false, false);
            compositeDisposable.add(injectPermission());

        }


    }

    private Disposable injectPermission() {
        return Single.create((SingleOnSubscribe<File>) emitter -> {
            File file = UsbPermission.copyAssets(getContext());
            if (file == null) {
                throw new FileNotFoundException("USB权限文件解压失败");
            }
            emitter.onSuccess(file);
        }).flatMapCompletable(file -> {
            CmdUtils.CommandResult commandResult = UsbPermission.copyApk(file);
            if (!(commandResult.result != -1 && UsbPermission.checkUsbFile())) {
                throw new FileNotFoundException("USB权限加载失败");
            }
            return Completable.complete();
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(() -> {
            if (progressDialog != null) progressDialog.dismiss();
            new AlertDialog.Builder(DialogActivity.this).setTitle("提示").setMessage("首次使用加载USB权限模块，点击确定将重启机器，激活USB模块").setCancelable(false).setPositiveButton("确定", (dialog, which) -> UsbPermission.reBoot()).show();
        }, throwable -> {
            if (progressDialog != null) {
                progressDialog.setMessage("USB权限加载失败");
                progressDialog.setProgress(100);
            }
            compositeDisposable.add(Completable.timer(5, TimeUnit.SECONDS).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(() -> {
                if (progressDialog != null) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
                finish();

            }));
        });

    }

    public Context getContext() {
        return this;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        compositeDisposable.dispose();
    }
}
